// 说明：现代化自定义滚动容器（基于 react-scrollbars-custom）
// 作用：统一滚动体验 + 主题化 + 支持“内容层”的 overscroll 行为（防穿透）

import React, { useState, useCallback } from 'react';
import { Scrollbar } from 'react-scrollbars-custom';
import { cn } from '@/lib/utils';

// 说明：滚动条主题类型
type ScrollbarTheme = 'default' | 'minimal' | 'bold';

// 说明：主题配置
interface ThemeConfig {
    trackWidth: string;
    thumbClasses: string;
    trackClasses: string;
}

// 说明：Props
interface ScrollContainerProps {
    children: React.ReactNode;
    className?: string;             // 说明：外层包装器（非滚动层）的类
    contentClassName?: string;      // 说明：内容区包装器（加内边距等）
    native?: boolean;
    momentum?: boolean;
    padRightForScrollbar?: boolean;

    autoHideScrollbar?: boolean;
    enableVerticalScroll?: boolean;
    enableHorizontalScroll?: boolean;
    scrollbarTheme?: ScrollbarTheme;
    minimalThumbSize?: number;

    // 说明：控制“真正可滚动层”的 overscroll 行为；默认 contain 防穿透
    overscrollBehavior?: 'auto' | 'contain' | 'none';

    // 透传给 <Scrollbar>
    [key: string]: any;
}

export const ScrollContainer: React.FC<ScrollContainerProps> = ({
    children,
    className,
    contentClassName,
    native = false,
    momentum = true,
    padRightForScrollbar = true,

    autoHideScrollbar = true,
    enableVerticalScroll = true,
    enableHorizontalScroll = false,
    scrollbarTheme = 'default',
    minimalThumbSize = 20,

    // 说明：默认防穿透
    overscrollBehavior = 'contain',

    ...props
}) => {
    // 说明：主题表
    const themeConfig: Record<ScrollbarTheme, ThemeConfig> = {
        default: {
            trackWidth: '7px',
            thumbClasses: 'bg-gray-400 opacity-30 transition-opacity',
            trackClasses: 'bg-transparent'
        },
        minimal: {
            trackWidth: '4px',
            thumbClasses: 'bg-gray-300 opacity-20 transition-opacity',
            trackClasses: 'bg-transparent'
        },
        bold: {
            trackWidth: '10px',
            thumbClasses: 'bg-gray-500 opacity-40 transition-opacity',
            trackClasses: 'bg-gray-100 opacity-50'
        }
    };

    const currentTheme = themeConfig[scrollbarTheme];

    // 说明：局部 hover 状态（用于自动隐藏 thumb）
    const [hovered, setHovered] = useState(false);
    const handleMouseEnter = useCallback(() => setHovered(true), []);
    const handleMouseLeave = useCallback(() => setHovered(false), []);

    return (
        // 说明：外层仅负责“占位/定高”，不负责滚动
        <div
            className={cn('scroll-container-wrapper', className)}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
        >
            <Scrollbar
                className={cn('w-full h-full')}
                native={native}
                momentum={momentum}
                noScrollY={!enableVerticalScroll}
                noScrollX={!enableHorizontalScroll}
                minimalThumbSize={minimalThumbSize}
                // 说明：把 overscroll 行为加到“真正滚动的 content 层”
                contentProps={{
                    className: cn(
                        // Tailwind 里无法动态映射到 overscroll-behavior 的具体值，这里用内联 style 保守落地
                        contentClassName
                    ),
                    style: { overscrollBehavior }
                }}
                trackYProps={{
                    className: cn(
                        'absolute right-0 top-0 bottom-0 rounded-md',
                        currentTheme.trackClasses
                    ),
                    style: {
                        width: currentTheme.trackWidth,
                        backgroundColor: 'transparent',
                        boxShadow: 'none',
                        border: 'none'
                    }
                }}
                thumbYProps={{
                    className: cn(
                        'relative block w-full min-h-5 rounded-md',
                        currentTheme.thumbClasses,
                        autoHideScrollbar && hovered && 'opacity-70'
                    )
                }}
                removeTracksWhenNotUsed
                removeTrackYWhenNotUsed
                {...props}
            >
                {/* 说明：内容区可选右侧留白，避免与自定义滚动条重叠 */}
                <div className={cn(!native && padRightForScrollbar && 'p-1', contentClassName)}>
                    {children}
                </div>
            </Scrollbar>
        </div>
    );
};
